package study.springcloud.gateway.support.predicate;

import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.gateway.handler.predicate.AbstractRoutePredicateFactory;
import org.springframework.http.HttpHeaders;
import org.springframework.web.server.ServerWebExchange;

import java.util.Collections;
import java.util.List;
import java.util.function.Predicate;

/**
 * 自定义断言
 * （1）命名需要以 RoutePredicateFactory 结尾，比如 CheckAuthRoutePredicateFactory
 * （2）使用的时候 CheckAuth 就是这个路由断言工厂的名称
 */
@Slf4j
public class CustomRoutePredicateFactory extends AbstractRoutePredicateFactory<CustomRoutePredicateFactory.Config> {

    public CustomRoutePredicateFactory() {
        super(Config.class);
    }

    @Override
    public List<String> shortcutFieldOrder() {
        return Collections.singletonList("name");
    }

    @Override
    public Predicate<ServerWebExchange> apply(Config config) {
        return new CustomRoutePredicate(config);
    }

    /**
     * （★）断言
     * （1）
     */
    public class CustomRoutePredicate implements Predicate<ServerWebExchange> {

        private Config config;

        public CustomRoutePredicate(Config config) {
            this.config = config;
        }

        @Override
        public boolean test(ServerWebExchange exchange) {
            //判断header里有放token
            HttpHeaders headers = exchange.getRequest().getHeaders();
            List<String> header = headers.get(config.getName());
            log.info("Token Predicate headers:{}", header);
            return header.size() > 0;
        }
    }

    /**
     * （★）配置
     */
    @Data
    public class Config {

        private String name;

    }
}
